﻿using IronPython.Hosting;
using Microsoft.Scripting.Hosting;

namespace Patriq.Msmq.Router.Core
{
    public interface IScriptEngine
    {
        void ReLoadScript();
        dynamic GetMethodByName(string methodName);
    }

    public class PythonScriptEngine : IScriptEngine
    {
        private readonly ScriptEngine scriptEngine;
        private readonly ScriptScope scriptScope;
        private readonly ScriptSource logicScriptSource;
        private readonly ScriptSource dataScriptSource;


        public PythonScriptEngine(string logicScriptFileName, string dataScriptFileName)
        {
            scriptEngine = Python.CreateEngine();
            scriptScope = scriptEngine.CreateScope();
            dataScriptSource = scriptEngine.CreateScriptSourceFromFile(dataScriptFileName);
            logicScriptSource = scriptEngine.CreateScriptSourceFromFile(logicScriptFileName);
            ReLoadScript();
        }

        public void ReLoadScript()
        {
            dataScriptSource.Execute(scriptScope);
            logicScriptSource.Execute(scriptScope);
        }

        public dynamic GetMethodByName(string methodName)
        {
            return scriptScope.GetVariable(methodName);
        }
    }
}